using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using CUtil;
using System.Reflection;
using CStock;

namespace CGrid
{
    /// <summary>
    /// Summary description for GridBase.
    /// </summary>
    public class GridBase : System.Windows.Forms.UserControl, IGrid
    {
        #region attributes

        
        object selectedObject;

        protected IProgramContext programContext;

        protected SourceGrid.Cells.Editors.EditorBase[] editors;
        SourceGrid.Cells.Views.Cell[] views;


        protected SourceGrid.Grid grid1;
        protected SourceGrid.Cells.Editors.EditorBase editorInt;
        protected SourceGrid.Cells.Editors.EditorBase editorString;
        protected SourceGrid.Cells.Editors.TextBoxUITypeEditor editorDateTime;
        protected SourceGrid.Cells.Editors.EditorBase editordouble;
        protected SourceGrid.Cells.Editors.EditorBase editorCurrency;
        SourceGrid.Cells.Views.Cell viewCell ;
        SourceGrid.Cells.Views.Cell viewCellDouble;
        SourceGrid.Cells.Views.Cell viewCellString;
        SourceGrid.Cells.Views.Cell viewCellRed;
        SourceGrid.Cells.Views.Cell viewCellGreen;
        SourceGrid.Cells.Views.ColumnHeader viewColumnHeader;


        Type typeEditorDouble;

        protected SourceGrid.Cells.ICellVirtual[] row;
        protected System.Collections.Specialized.NameValueCollection columnHeader;


        bool readOnly;
        bool multiline;
        
        bool initialized;

        protected bool cellsReadOnly;

        private GridTypes gridType;

        #endregion

        #region constructor

        public GridBase()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();

            
            //DevAge.Drawing.VisualElements.ColumnHeader backHeader = new DevAge.Drawing.VisualElements.ColumnHeader();
            
            
            editorInt = SourceGrid.Cells.Editors.Factory.Create(typeof(int));
            //editorInt.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.DoubleClick;
            editorInt.EditableMode = SourceGrid.EditableMode.AnyKey;


            editorString = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
            editorString.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.DoubleClick;
            editorString.EditableMode = SourceGrid.EditableMode.AnyKey;

            editorDateTime = new SourceGrid.Cells.Editors.TextBoxUITypeEditor(typeof(DateTime));
            
            editorDateTime.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.DoubleClick;

            //editordouble = SourceGrid.Cells.Editors.Factory.Create(typeof(double));
            //editordouble.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.DoubleClick;
            editordouble = new SourceGrid.Cells.Editors.TextBox(typeof(double));
            DevAge.ComponentModel.Converter.NumberTypeConverter numberFormatCustom = new DevAge.ComponentModel.Converter.NumberTypeConverter(typeof(double));
            //numberFormatCustom = new DevAge.ComponentModel.Converter.NumberTypeConverter(typeof(double));
            numberFormatCustom.Format = "#.00";
            //numberFormatCustom.Format = "#.00";
            editordouble.TypeConverter = numberFormatCustom;
            editordouble.AllowNull = true;
            editordouble.AllowStringConversion = true;

            //SourceGrid.Cells.Views.Cell captionModel = new SourceGrid.Cells.Views.Cell();

            //editorCurrency = SourceGrid.Cells.Editors.Factory.Create(typeof(CurrencyManager));
            //editorInt.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.DoubleClick;
            editorInt.EditableMode = SourceGrid.EditableMode.AnyKey;

            columnHeader = new System.Collections.Specialized.NameValueCollection();

            viewCell = new SourceGrid.Cells.Views.Cell();
            viewCell.BackColor = Color.Snow;
            viewCell.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;

            this.viewCellDouble = new SourceGrid.Cells.Views.Cell();

            viewCellRed = new SourceGrid.Cells.Views.Cell();
            viewCellRed.BackColor = Color.Red;
            viewCellRed.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;

            viewCellGreen = new SourceGrid.Cells.Views.Cell();
            viewCellGreen.BackColor = Color.Green;
            viewCellGreen.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;

            viewCellString = new SourceGrid.Cells.Views.Cell();
            viewCell.BackColor = Color.Snow;
            viewCellString.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleLeft;
            
            viewColumnHeader = new SourceGrid.Cells.Views.ColumnHeader();
            viewColumnHeader.BackColor = Color.DarkGray;
            //grid1.SelectionMode = SourceGrid.GridSelectionMode.Row;
            typeEditorDouble = this.editordouble.GetType();
            this.grid1.SpecialKeys = SourceGrid.GridSpecialKeys.Default;

        }

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {

            base.Dispose(disposing);
        }
        #endregion

        #region properties

        public GridTypes GridType
        {
            get
            {
                return this.gridType;
            }
            set
            {
                this.gridType = value;
            }
        }

        /// <summary>
        /// dataholder - the main source of data
        /// </summary>
        public IProgramContext ProgramContext
        {
            get
            {
                return this.programContext;
            }
            set
            {
                programContext = value;

            }
        }
          /// <summary>
        /// dataholder - the main source of data
        /// </summary>
        public object SelectedObject
        {
            get
            {
                try
                {
                    this.GetObjectFromGrid();
                }
                catch (Exception ex)
                {
                    Debug.Assert(false, "Error in setting selected object " + ex.Message);

                }
                return this.selectedObject;
            }
            set
            {
                selectedObject = value;

            }
        }
        public bool CellsReadOnly
        {
            get
            {
                return this.cellsReadOnly;
            }
            set
            {
                if (cellsReadOnly != value)
                {
                    this.cellsReadOnly = value;
                    for (int r = 0; r < this.grid1.RowsCount; r++)
                    {
                        for (int c = 0; c < grid1.ColumnsCount; c++)
                        {
                            if (grid1[r, c].Editor != null)
                            {
                                if (grid1[r, c].Editor.EnableEdit == true)
                                    grid1[r, c].Editor.EnableEdit = !cellsReadOnly;
                            }
                        }
                    }
                }
            }

        }

        #endregion

        #region Grid creation

        public bool CreateGrid(CUtil.GridTypes myGridType, bool assembly)
        {
            ClearGridComplete();
            this.gridType = myGridType;
            if(assembly)
			{

                Type t = this.GetType();
                Assembly ass = t.Assembly;
                
                string xmlResource = "EForms.Grid_ConfigXML.";
                xmlResource += gridType.ToString() + ".xml";
                if (CreateGridFromXMLFile(xmlResource))
                {
                    this.initialized = true;
                    return true;
                }
			}
            else
			{
				try
				{
                    string xmlResource = AppDomain.CurrentDomain.BaseDirectory + "\\";
				
					xmlResource += gridType.ToString() + ".xml";
                    if (this.CreateGridFromXMLFile(xmlResource))
                    {
                        this.initialized = true;
                        return true;
                    }
					
				}
				catch(Exception exc)
				{
					Debug.Assert(false, exc.Message);
					return false;

				}
			}

            return false;
            

            //ClearGridComplete();

          

        }
        private void CreateColumn_Number()
        {
            
            SourceGrid.Cells.ColumnHeader header = new SourceGrid.Cells.ColumnHeader("No");
            header.Value = "No";
            header.View = this.viewColumnHeader;
            //header.AutomaticSortEnabled = true;
            header.View.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleLeft;

            grid1[0, 0] = header;
            
            grid1.Columns[0].AutoSizeMode = SourceGrid.AutoSizeMode.None;
            grid1.Columns[0].Width = 30;
           

            this.columnHeader.Add("index", "No");

            this.editors[0] = editorString;
            this.views[0] = this.viewColumnHeader;


        }
        private void CreateColumn_Name()
        {
            SourceGrid.Cells.ColumnHeader header = new SourceGrid.Cells.ColumnHeader("Name");
            //header.AutomaticSortEnabled = false;
            //header.Value = "Name";
            header.View = this.viewColumnHeader;
            header.View.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleLeft;

            grid1[0, 1] = header;
            grid1.Columns[1].AutoSizeMode = SourceGrid.AutoSizeMode.None;
            grid1.Columns[1].Width = 30;
            

            this.columnHeader.Add("index", "Name");

            this.editors[1] = editorString;
            this.views[1] = this.viewColumnHeader;

        }
        private void CreateColumn_Custom(int i, NameObjectCollection nameObjectColl)
        {
            //string strDisplay = ;
            string columnName = nameObjectColl.Keys[i - 2].ToString();
            this.columnHeader.Add(columnName, columnName);

            SourceGrid.Cells.ColumnHeader header = new SourceGrid.Cells.ColumnHeader(i);
            //header.AutomaticSortEnabled = true;
            header.Value = columnName;
            header.View = this.viewColumnHeader;
            header.View.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;

            grid1[0, i] = header;

            grid1.Columns[i].AutoSizeMode = SourceGrid.AutoSizeMode.None;
            grid1.Columns[i].Width = 30;
            
            //grid1[0, 0].Model.ValueModel ;

            this.editors[i] = editorString;
            this.views[i] = this.viewCell;


            this.columnHeader.Add("index", "No");

            

        }
        private void GridInitFirst(int numberOfColumns)
        {
            ClearGridComplete();
            grid1.RowsCount = 1;
       
            //3. create the columns
            this.editors = new SourceGrid.Cells.Editors.EditorBase[numberOfColumns];
            this.views = new SourceGrid.Cells.Views.Cell[numberOfColumns];



            //grid1.FixedRows = 1;
            grid1.SelectionMode = SourceGrid.GridSelectionMode.Row;
            grid1.AutoStretchColumnsToFitWidth = true;

        }
        private void Grid_LastInits()
        {
            grid1.AutoStretchColumnsToFitWidth = true;
            grid1.AutoSizeCells();
            grid1.Columns.StretchToFit();

        }
        public bool CreateGrid(NameObjectCollection nameObjectColl)
        {
            
            grid1.ColumnsCount = nameObjectColl.Count + 2;
            GridInitFirst(grid1.ColumnsCount);
            //creates a grid with columns as corresponding to the items in the NameObjectCollection
            //the first column is the standard "No" column

           
            //beware : the first column is for the index !
            //beware : the second column is for the share name!


            //3. create the columns

            //first column is index
            CreateColumn_Number();
            CreateColumn_Name();

            for (int i = 2; i < grid1.Columns.Count; i++)
            {

              CreateColumn_Custom(i, nameObjectColl);

            }
            Grid_LastInits();
           
            return true;
        }
        private void CreateColumn_Custom(int i, System.Xml.XmlNode xmlNode)
        {
            string columnName = xmlNode.Name;
            string columnDisplayName = xmlNode.Attributes[0].Value.ToString();
            this.columnHeader.Add(columnName, columnDisplayName);


            SourceGrid.Cells.ColumnHeader header = new SourceGrid.Cells.ColumnHeader(i);
            //header.AutomaticSortEnabled = false;
            header.Value = columnDisplayName;
            header.View = this.viewColumnHeader;
            header.View.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;

            grid1[0, i] = header;

            string s = xmlNode.Attributes[1].Value.ToString();

            //the columsHeader is a collections with the caption of the columns

            switch (s)
            {
                case ("int"):
                    {
                        editors[i] = this.editorInt;
                        this.views[i] = this.viewCell;
                        //this.views[i].TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
                        break;
                    }
                case ("string"):
                    {
                        editors[i] = this.editorString;
                        this.views[i] = this.viewCellString;
                        break;
                    }
                case ("DateTime"):
                    {
                        editors[i] = this.editorDateTime;
                        this.views[i] = this.viewCell;
                        this.views[i].TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
                        break;
                    }
              
                case ("double"):
                    {
                        editors[i] = this.editordouble;
                        this.views[i] = this.viewCell;
                        this.views[i].TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;

                        break;
                    }

            }
            editors[i].EnableEdit = false;

        }
        private bool CreateGridFromXMLFile(string xmlResource)
        {
            

            //1. read xml file for the templae
            System.Xml.XmlDocument xmlDoc = ReadXMLFile(xmlResource);
            if (xmlDoc == null)
                return false;

            //3. Create the grid with default initialization

            System.Xml.XmlNodeList rowListInit = xmlDoc.SelectNodes("//CellModel");
            System.Xml.XmlNode testNode = rowListInit.Item(0);
            System.Xml.XmlNodeList columnNodes = testNode.ChildNodes;
            grid1.ColumnsCount = columnNodes.Count + 1;

            GridInitFirst(grid1.ColumnsCount);

            grid1.RowsCount = 1;
            System.Xml.XmlNodeList rowList = xmlDoc.SelectNodes("//row");


            CreateColumn_Number();
            //CreateColumn_Name();


            for (int i = 1; i < grid1.Columns.Count; i++)
            {

                System.Xml.XmlNode xmlNode = columnNodes[i - 1];
                this.CreateColumn_Custom(i, xmlNode);
                

            }


            Grid_LastInits();
            

            return true;

        }


        private System.Xml.XmlDocument ReadXMLFile(string xmlResource)
        {

            //---------------------------
            //1. Read xml data
            //read xml
            System.IO.StreamReader streamReader = null;
            try
            {
                streamReader = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(xmlResource));
            }
            catch (Exception exc)
            {
                System.Windows.Forms.MessageBox.Show("Software error - there is a file missing for the grid creation " + xmlResource + " ; " + exc.Message);
                return null;
            }
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(streamReader.ReadToEnd());
            streamReader.Close();
            return xmlDoc;

        }
        public void AddRowAndRefresh(object o, bool setCellColor)
        {
            this.AddRow_Single(o, setCellColor);
            this.RefreshGrid();

        }


        public void AddRow_Single(object o, bool setCellColor)
        {
            if (o != null)
            {
                AddRow_SingleHelper(o, setCellColor);
            }
            else
            {
                AddRowEmpty();
            }

        }
        public void AddRow_Single_Update(object o, int rowindex )
        {
            if (o != null)
            {
                AddRow_SingleHelper_Update(o, rowindex, true);
            }
            else
            {
                AddRowEmpty();
            }

        }
        public void AddRow_ForEachProperty(object o)
        {
            this.selectedObject = o;

            if (o != null)
            {
                this.AddRow_AllSerializableProperties(o);
            }
            else
            {
                AddRowEmpty();
            }

        }
        private int FindRowIndex(string name)
        {
            for (int i = 0; i < this.columnHeader.Count; i++)
            {
                if (name == this.columnHeader.GetKey(i).ToString())
                {
                    return i;
                }

            }

            return -1;

        }
        //private void SetRow(SourceGrid.Cells.ICellVirtual[] row )
        //{
        //    for (int i = 1; i <= editors.GetLength(0); i++)
        //    {
        //        SourceGrid.Cells.ICellVirtual c = row[i] as SourceGrid.Cells.ICellVirtual;
        //        grid1[grid1.RowsCount, i ].Value = c.ToString();

        //        grid1[grid1.RowsCount, i].Editor = this.editors[i];
        //        grid1[grid1.RowsCount, i].View = this.views[i];

                
        //    }

        //}
        private void AddRowsFromXML(string xmlResource)
        {

            System.Xml.XmlDocument xmlDoc = ReadXMLFile(xmlResource);
            if (xmlDoc == null)
                return;

            System.Xml.XmlNodeList rowListInit = xmlDoc.SelectNodes("//CellModel");

            row = new SourceGrid.Cells.ICellVirtual[this.grid1.Columns.Count];
            int rowListCount = grid1.Rows.Count;
            //add first row
            //------------------------------
            System.Xml.XmlNodeList rowList = xmlDoc.SelectNodes("//row1");
            grid1.Rows.Insert(grid1.RowsCount);
            foreach (System.Xml.XmlNode node in rowList)
            {

                for (int i = 1; i < editors.GetLength(0); i++)
                {

                  

                    grid1[grid1.RowsCount, i].Value = node.Attributes[i - 1].InnerText;
                    grid1[grid1.RowsCount, i].Editor = this.editors[i];
                    grid1[grid1.RowsCount, i].View = this.views[i];

                   
                }
                //rowListCount++;
            }
            
           


            //add second row
            //------------------------------
            grid1.Rows.Insert(grid1.RowsCount);
            rowList = xmlDoc.SelectNodes("//row2");
            foreach (System.Xml.XmlNode node in rowList)
            {

                for (int i = 1; i <= editors.GetLength(0); i++)
                {



                    grid1[grid1.RowsCount, i].Value = node.Attributes[i - 1].InnerText;
                    grid1[grid1.RowsCount, i].Editor = this.editors[i];
                    grid1[grid1.RowsCount, i].View = this.views[i];

                   
                }
                //rowListCount++;
            }
           



        }
        public void RefreshGrid()
        {
            //grid1.Rows[grid1.RowsCount - 1].Focus();
            grid1.AutoSizeCells();
        }
        private void AddRowEmpty()
        {
            row = new SourceGrid.Cells.ICellVirtual[this.grid1.Columns.Count];
            SourceGrid.Cells.Cell c = CreateIndexCell(this.grid1.RowsCount);
            grid1[0, 0] = c;


            //fill rows with empty cells
            grid1.Rows.Insert(grid1.RowsCount);
            for (int i = 0; i < this.grid1.Columns.Count; i++)
            {
                grid1[grid1.RowsCount, i].Value = null;
            }
            
        }
        private void AddRow_AllSerializableProperties(object o)
        {
            Type t = o.GetType();
            System.Reflection.PropertyInfo[] parr = t.GetProperties();

            
            string pName = string.Empty;
            object propVal = null;
            try
            {
                //get values from the class
                for (int i = 0; i < parr.GetLength(0); i++)
                {
                    try
                    {
                        System.Reflection.PropertyInfo pinfo = parr[i];
                        //Debug.WriteLine("Serializable " + pinfo.PropertyType.IsSerializable.ToString());
                        //if (pinfo.PropertyType.IsSerializable)
                        if (pinfo.PropertyType.IsSerializable)
                        {
                            pName = parr[i].Name;
                            propVal = parr[i].GetValue(o, null);

                            //row with 2 columns
                            //----------------------------------------------
                            //first cell
                            row = new SourceGrid.Cells.ICellVirtual[3];
                            SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell();

                            c = CreateIndexCell(this.grid1.RowsCount);

                            c = new SourceGrid.Cells.Cell();
                            c.Value =  pName;
                            c.View.BackColor = System.Drawing.Color.WhiteSmoke;

                            row[1] = c;
                            //-----------------------------------
                            //second cell
                            
                           
                            
                            grid1.Rows.Insert(grid1.RowsCount);
                           
                            SourceGrid.Cells.Cell cll = CreateCellWithCustomFormat();
                            cll.Editor = this.editordouble;
                            cll.Editor.EnableEdit = true;
                            cll.View = this.views[2];

                            grid1[grid1.RowsCount, i] = cll;

                           

                            if (!(propVal.GetType().BaseType == typeof(System.Collections.ArrayList)))
                            {
                                grid1[grid1.RowsCount, 2].Value = propVal;
                                row[2] = c;
                            }
                            Debug.WriteLine(propVal.GetType().BaseType.ToString());
                            

                        }

                        
                        
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                        //do not set value if exception caught - for instance with arrayList
                    }
                   



                }
            }
            catch (Exception exc)
            {
                Debug.Assert(false, "Error while setting " + pName, exc.Message);
            }

            //insert row
           


        }
        private bool GetObjectFromGrid()
        {
            if (this.selectedObject == null)
            {
                return false;
            }
            Type t = this.selectedObject.GetType();
            System.Reflection.PropertyInfo[] parr = t.GetProperties();


            string pName = string.Empty;
            //object propVal = null;
            try
            {
                //get values from the class
                for (int i = 0; i < parr.GetLength(0); i++)
                {
                    try
                    {
                        System.Reflection.PropertyInfo pinfo = parr[i];
                        Debug.WriteLine("Serializable " + pinfo.PropertyType.IsSerializable.ToString());
                        string propName_FromClass = pinfo.Name;

                        if (pinfo.PropertyType.IsSerializable)
                        {
                            //loop cells
                            for (int r = 1; r < this.grid1.RowsCount; r++)
                            {
                                //get name of the property
                                string propName_FromCell = grid1[r, 1].Value.ToString();
                                if (propName_FromCell == propName_FromClass)
                                {
                                    object propValue = grid1[r, 2].Value;
                                    pinfo.SetValue(this.selectedObject, propValue, null);


                                }


                            }



                        }


                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                        return false;
                        //do not set value if exception caught - for instance with arrayList
                    }




                }
            }
            catch (Exception exc)
            {
                Debug.Assert(false, "Error while setting " + pName, exc.Message);
                return false;
            }

            //insert row
            return true;
        

        }
        private void InsertEmptyRow()
        {
            try
            {

                row = new SourceGrid.Cells.ICellVirtual[this.grid1.Columns.Count];
                SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell();
                c = CreateIndexCell(this.grid1.RowsCount);
                grid1[grid1.RowsCount - 1, 0] = c;


                //fill rows with empty cells
                for (int i = 1; i < this.grid1.Columns.Count; i++)
                {
                    c = CreateCellWithCustomFormat();
                    grid1[grid1.RowsCount - 1, i] = c;

                }
            }
            catch (Exception err)
            {
                Debug.Assert(false, "Error inserting empty row in grid : " + err.Message);
            }

        }
  

        public void AddRowsFromCollection(string name, NameObjectCollection coll)
        {
            if (coll.Count < 1)
                return;

            row = new SourceGrid.Cells.ICellVirtual[this.grid1.Columns.Count];
            SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell();
            c = CreateIndexCell(this.grid1.RowsCount);


            //insert name
            SourceGrid.Cells.Cell c1 = new SourceGrid.Cells.Cell();
            c1.Editor = this.editors[1];
            c1.View = this.views[1];
            c1.Value =  name;
            row[1] = c1;

            //fill rows with empty cells
            for (int i = 2; i < this.grid1.Columns.Count; i++)
            {
                c = CreateCellWithCustomFormat();// new SourceGrid.Cells.Cell();
                c.Value = null;
                row[i] = c;
            }

            //get values from the collection
            grid1.Rows.Insert(grid1.RowsCount);
            for (int i = 2; i < this.grid1.Columns.Count; i++)
            {
                //c = new SourceGrid.Cells.Cell();

                
                //object val = coll[i -2];
                string cName = this.columnHeader.GetKey(i - 2).ToString();
                object val = coll[cName];

                grid1[grid1.RowsCount, i].Editor = this.editors[i];
                SourceGrid.Cells.Cell cll = CreateCellWithCustomFormat();
                cll.View = this.views[i];
                cll.Value = val;
                grid1[grid1.RowsCount, i] = cll;


            }

            //insert row
            

        }
        private SourceGrid.Cells.Cell CreateCellWithCustomFormat()
        {

            //SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell();
            SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell("Format #.00");
          
            return c;

        }
        private SourceGrid.Cells.Cell CreateCellWithCustomFormat_CheckEditor(int indexOfEditor)
        {
            SourceGrid.Cells.Cell c;
            if (this.editors[indexOfEditor] == this.editordouble)
            {
                c = new SourceGrid.Cells.Cell("Format #.00");
            }
            else
            {
                c = new SourceGrid.Cells.Cell();
            }
            return c;

        }
        private SourceGrid.Cells.Cell CreateIndexCell(int index)
        {
            try
            {
                SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell();
                c.Editor = this.editors[0];
                c.View = this.views[0];
                c.Value = index - 1;
                return c;
            }
            catch (Exception err)
            {
                Debug.Assert(false, "error in Creating Index Cell : " + err.Message);
                return null;
            }
        }
        protected void SetCellValueWithColor(int i, int j, object val)
        {

            double oldVal = Convert.ToDouble(grid1[i, j].Value);
            double newVal = Convert.ToDouble(val);
            grid1[i, j].Value = val;
            if (newVal > oldVal)
            {
                grid1[i, j].View.BackColor = System.Drawing.Color.Green;
            }
            else if (newVal < oldVal)
            {
                grid1[i, j].View.BackColor = System.Drawing.Color.Red;
            }
            else
            {
                grid1[i, j].View.BackColor = System.Drawing.Color.White;
            }


        }
        

        #endregion

        #region Component Designer generated code
        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.grid1 = new SourceGrid.Grid();
            this.SuspendLayout();
            // 
            // grid1
            // 
            //this.grid1.AutoSizeMinHeight = 10;
            //this.grid1.AutoSizeMinWidth = 10;
            this.grid1.AutoStretchColumnsToFitWidth = false;
            this.grid1.BackColor = System.Drawing.Color.WhiteSmoke;

            //this.grid1.CustomScrollArea = new System.Drawing.Size(0, 0);
            //this.grid1.CustomScrollPosition = new System.Drawing.Point(0, 0);
            this.grid1.Dock = System.Windows.Forms.DockStyle.Fill;

            this.grid1.FixedRows = 0;

            //this.grid1.GridScrollPosition = new System.Drawing.Point(0, 0);
            this.grid1.Location = new System.Drawing.Point(0, 0);
            this.grid1.Name = "grid1";
            //this.grid1.Redraw = true;

            this.grid1.Size = new System.Drawing.Size(624, 320);
            this.grid1.TabIndex = 1;

            // 
            // SourceGridBase
            // 
            this.Controls.Add(this.grid1);
            this.Name = "SourceGridBase";
            this.Size = new System.Drawing.Size(624, 320);
            this.ResumeLayout(false);

        }
        #endregion

        #region members

        public void ClearGridComplete()
        {
            try
            {
                if (this.grid1.Rows != null && this.grid1.Rows.Count > 0)
                {
                    if (this.grid1.Rows.Count == 1)
                        this.grid1.Rows.Remove(0);
                    else
                    {
                    this.grid1.Rows.RemoveRange(0, this.grid1.Rows.Count - 1);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error removing grid rows " + ex.Message);

            }
            columnHeader = new System.Collections.Specialized.NameValueCollection();
        }
        public void ClearGridRows()
        {
            if (this.grid1.Rows != null && this.grid1.Rows.Count > 1)
            {
                this.grid1.Rows.RemoveRange(1, this.grid1.Rows.Count - 1);
            }
        }
        #endregion

       
        public bool ReadOnly
        {
            get
            {
                return this.readOnly;
            }
            set
            {
                readOnly = value;
            }
        }
        public bool Initialized
        {
            get
            {
                return this.initialized;
            }
            set
            {
                initialized = value;
            }
        }
        
        public bool Multiline
        {
            get
            {
                return this.multiline;
            }
            set
            {
                multiline = value;
            }
        }
        /// <summary>
        /// take care : each object should implement this!!
        /// </summary>
        /// <returns></returns>
        public object GetFromAssembly()
        {
            // create new settings class and copy all public properties values to clone

            object s = null;
            try
            {

                Type t = this.GetType();
                Assembly ass = t.Assembly;

                string className = t.Name;
                s = ReflectionClass.CreateInstanceOfClassFromAssembly(ass, className);

                foreach (System.Reflection.PropertyInfo pi in s.GetType().GetProperties())
                {
                    //ignore errors
                    //for instance the this property (indexer) cannot be set
                    try
                    {
                        
                        //pi.Value = (s, this.GetType().GetProperty(pi.Name).GetValue(this, null), null);
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.Message);

                        //ignore exceptions!
                    }

                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message);
                //Debug.Assert(false, "Error cloning object " + this.name, exc.Message);
            }
            return s;
        }
        protected void SetCellColor(object oldVal, object nevVal, SourceGrid.Cells.Cell c)
        {
            double fOld = 0f;
            double fNew = 0f;
            try
            {
                if (oldVal != null && oldVal.ToString() == "Format #.00")
                {
                    oldVal = 0f;
                }
                fOld = Convert.ToDouble(oldVal);
                fNew = Convert.ToDouble(nevVal);
                if (fNew > fOld)
                {
                    c.View = this.viewCellGreen;
                    
                }
                else if (fNew < fOld)
                {

                    c.View = this.viewCellRed;

                }
                else
                {
                    c.View = this.viewCell;
                }

            }
            catch
            {
                Console.WriteLine("Exception setting color in Grid for cell: " + c.Value.ToString());
                return;

            }

        }
        private void SetBackColorOfCell(int index, object val, SourceGrid.Cells.Cell c)
        {
            if (grid1[0, index].Value.ToString() == "Change%")
            {
                if (c.Editor.GetType() == this.typeEditorDouble)
                {
                    SetCellColor(grid1[grid1.RowsCount - 1, index].Value, val, c);
                }
            }
            if (grid1[0, index].Value.ToString() == "Performance")
            {
                if (c.Editor.GetType() == this.typeEditorDouble)
                {
                    SetCellColor(grid1[grid1.RowsCount - 1, index].Value, val, c);
                }
            }
        }
        private void AddRow_SingleHelper_Update(object o, int rowindex, bool setColor)
        {
            string parName = string.Empty;
            try
            {
                Type t = o.GetType();
                System.Reflection.PropertyInfo[] parr = t.GetProperties();

                SourceGrid.Cells.Cell c = CreateIndexCell(rowindex);
              
                if (grid1.RowsCount >= rowindex)
                {
                    grid1[rowindex - 1, 0] = c;

                    //get values from the class and put them in the row

                    for (int i = 0; i < parr.GetLength(0); i++)
                    {
                        //SetCellValue(o, parr, i);
                        parName = parr[i].Name;
                        if (parName == null || parName == string.Empty || parName == @"")
                        {
                            System.Diagnostics.Debug.WriteLine("parname = empty " + parName);
                        }
                        else
                        {
                            int index = FindRowIndex(parName);
                            //SourceGrid.Cells.Cell c = new SourceGrid.Cells.Cell();
                            if (index > -1)
                            {
                                object val = parr[i].GetValue(o, null);
                                c = CreateCellWithCustomFormat();
                                c.Editor = this.editors[index];
                                c.View = this.views[index];
                                c.Value = val;
                                
                                if (setColor)
                                {
                                    SetBackColorOfCell(index, val, c);
                                }
                                

                                grid1[rowindex - 1, index] = c;



                            }
                        }


                    }
                }



            }
            catch (Exception ex)
            {
                //occurs for testcases
                Debug.Assert(false, "Error in writing grid result for: " + parName + "; " + ex.Message);

            }
        }
        private void AddRow_SingleHelper(object o, bool setCellColor)
        {
            grid1.Rows.Insert(grid1.RowsCount);
            InsertEmptyRow();
            AddRow_SingleHelper_Update(o, this.grid1.RowsCount, setCellColor);


        }
    }
  
}
